//
//  ALPS_PlayerMainViewController.m
//  Alps
//
//  Created by dllo on 16/6/12.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ALPS_PlayerMainViewController.h"
#import <MBProgressHUD.h>
#import "ALPS_PlayMusicModel.h"
#import "ALPS_SpecialDetailModel.h"
#import "ALPS_BaseViewController.h"

static ALPS_PlayStyle playStyle;

@interface ALPS_PlayerMainViewController ()<UITableViewDelegate, UITableViewDataSource>

// 添加在navbar上的label
@property (nonatomic, strong) UILabel *onNavBarLabel;
// 背景模糊图
@property (nonatomic, strong) UIImageView *backImgView;
// 旋转专辑图
@property (nonatomic, strong) UIImageView *SpecialImgView;
// 旋转图定时器
@property (nonatomic, strong) NSTimer *RotateImgTimer;
// 进度滑条
@property (nonatomic, strong) UISlider *slider;
// 滑条timer定时器
@property (nonatomic, strong) NSTimer *sliderTimer;
// 滑条左侧时间进度显示
@property (nonatomic, strong) UILabel *beginTimeLabel;
// 滑条右侧显示歌曲时长
@property (nonatomic, strong) UILabel *timeLongLabel;
/**
 *  播放or暂停 按钮
 */
@property (nonatomic, strong) UIButton *playButton;
// 上一曲按钮
@property (nonatomic, strong) UIButton *lastSongButton;
// 下一曲按钮
@property (nonatomic, strong) UIButton *nextSongButton;
// 单曲循环or随机播放or顺序播放按钮
@property (nonatomic, strong) UIButton *OneSongOrOrderButton;

/**
 *  监控当前播放模式
 */
//@property (nonatomic, assign) ALPS_PlayStyle playStyle;

// 播放列表按钮
@property (nonatomic, strong) UIButton *playListButton;

// 列表model
@property (nonatomic, strong) ALPS_PlayMusicModel *playListModel;
// 列表table的背景
@property (nonatomic, strong) UIView *pushedListView;
// 列表table
@property (nonatomic, strong) UITableView *musicListTableView;
// 监控list的当前页
@property (nonatomic, assign) NSInteger pageNumber;
// 列表cell上的正在播放图标
@property (nonatomic, strong) UIImageView *currentPlayingCellImgView;
@end

@implementation ALPS_PlayerMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    static ALPS_PlayerMainViewController *playerVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerVC = [[ALPS_PlayerMainViewController alloc] init];
        isPlaying = YES;
    });
    
    [self.sliderTimer invalidate];
    [self.RotateImgTimer invalidate];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.player = [ALPS_PlayMusicTool manager];
    
    // 建立UI (广播or音乐 在这里面判断是否创建那一堆按钮)
    [self createUI];
    
    
    if (self.isRedioYesOrNo == YES) // 如果是广播
    {
        [self.player pauseCurrentMusic];
        NSLog(@"点进来的这个是广播");
        NSLog(@" /////// %d %@ %@ %@", self.isRedioYesOrNo, self.radioName, self.pictureURL, self.radioURL);
        [self.SpecialImgView sd_setImageWithURL:[NSURL URLWithString:self.pictureURL]];
        self.navigationItem.title = self.radioName;
        [self.player playRadioWithURL:self.radioURL];
        [self.player playCurrentMusic];
        
        self.RotateImgTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(timerForRotateSpecialImgView) userInfo:nil repeats:YES];
        
        //添加中止广播按钮
        UIButton *stopradioButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [[self.view viewWithTag:100001] addSubview:stopradioButton];
        [stopradioButton setImage:[[UIImage imageNamed:@"player停止广播"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        [stopradioButton makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo([self.view viewWithTag:100001].centerX);
            make.width.and.right.equalTo(50);
            make.top.equalTo([self.view viewWithTag:100001].bottom).offset(-200);
        }];
        [stopradioButton addTarget:self action:@selector(didClickedStopRadio) forControlEvents:UIControlEventTouchUpInside];
    }
    else // 如果不是广播,那就是歌曲或者小说
    {
        NSLog(@"点进来的这个是歌曲/小说/讲坛(非广播)");
        
        self.navigationController.navigationBar.hidden = YES;
        
        [self getSongDataByTrackId:self.trackId];
        
        [self createMusicListTableView];
        
        NSLog(@"isPlaying ** %d", isPlaying);
    }
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(20, 20, 35, 50);
    [backButton setBackgroundImage:[UIImage imageNamed:@"btn_back_n"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(didClickedLeftBarButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    //通知中心
    NSString *trackId = [NSString stringWithFormat:@"%ld", self.trackId];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"trackId" object:trackId];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:self.pictureURL];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hidePlayView" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"radioURL" object:self.radioURL];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"radioImg" object:self.pictureURL];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"radioName" object:self.radioName];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:nil];
}

#pragma mark -- 停止广播点击方法
- (void)didClickedStopRadio
{
    [self.player pauseCurrentMusic];
    [self.RotateImgTimer invalidate];
    self.RotateImgTimer = nil;
}

#pragma mark -- 设置通知中心
- (void)setNotificationCenterByTrackId:(NSInteger)trackId
                              ImageURL:(NSString *)imageURL
{
    NSString *myTrackId = [NSString stringWithFormat:@"%ld", trackId];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"trackId" object:myTrackId];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:imageURL];
}

#pragma mark -- 返回上一页
- (void)didClickedLeftBarButton
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showPlayView" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -- 非广播数据请求
- (void)getSongDataByTrackId:(NSInteger)trackId
{
    NSString *urlStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/v1/track/baseInfo?device=iPhone&trackId=%ld", trackId];
    NSLog(@"%ld", trackId);
    
    [WSSNetTool GetNetByURL:urlStr body:nil headers:nil response:WSSJSON success:^(id result) {
        
        ALPS_PlayMusicModel *model = [[ALPS_PlayMusicModel alloc] initWithDic:result];
        [self setNotificationCenterByTrackId:trackId ImageURL:model.coverLarge];
        self.playListModel = model;
        
        [self giveValueWithModel:self.playListModel];
        
        [self.musicListTableView reloadData];
        
        CGFloat currentTime = CMTimeGetSeconds([self.player.player currentTime]);
        NSInteger minutes = (long)currentTime / 60;
        NSInteger seconds = (long)currentTime % 60;
        self.beginTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", minutes, seconds];
        
        self.slider.value = currentTime / model.duration;
        NSLog(@"^^^ %d", isPlaying);
        if (isPlaying)
        {
            [_playButton setImage:[[UIImage imageNamed:@"player暂停"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        }
        else
        {
            [_playButton setImage:[[UIImage imageNamed:@"play播放"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark -- UI
- (void)createUI
{
    // 背景图
    self.backImgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_backImgView];
    // 模糊效果
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = self.view.bounds;
    [self.view addSubview:effectView];
    effectView.tag = 100001;
    
    // 旋转专辑图的背景图
    UIView *specialBackView = [[UIView alloc] init];
    [effectView addSubview:specialBackView];
    [specialBackView makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.top.equalTo(self.view.top).offset(ScreeHeight / 6.0 - 4);
        make.width.and.height.equalTo(ScreeWidth * 0.7 + 8);
    }];
    specialBackView.backgroundColor = [UIColor grayColor];
    NSInteger radius = ScreeWidth * 0.35 + 4;
    specialBackView.layer.cornerRadius = radius;
    
    // 旋转专辑图
    self.SpecialImgView = [[UIImageView alloc] init];
    [effectView addSubview:_SpecialImgView];
    [self.SpecialImgView makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.top.equalTo(self.view.top).offset(ScreeHeight / 6.0);
        make.width.and.height.equalTo(ScreeWidth * 0.7);
    }];
    self.SpecialImgView.layer.cornerRadius = ScreeWidth * 0.35;
    self.SpecialImgView.layer.masksToBounds = YES;
    
    
    if (self.isRedioYesOrNo == NO) // 如果不是广播, 再加那一堆按钮
    {
        // 进度滑条
        self.slider = [[UISlider alloc] initWithFrame:CGRectMake(30, ScreeHeight * 0.75, ScreeWidth - 60, 20)];
        [effectView addSubview:_slider];
        [self.slider setThumbImage:[UIImage imageNamed:@"player播放进度"] forState:UIControlStateNormal];
        [self.slider addTarget:self action:@selector(sliderTimeChanged:) forControlEvents:UIControlEventValueChanged];
        
        
        //左侧进度
        self.beginTimeLabel = [[UILabel alloc] init];
        [effectView addSubview:_beginTimeLabel];
        [_beginTimeLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(effectView.left);
            make.right.equalTo(self.slider.left);
            make.centerY.equalTo(self.slider.centerY);
            make.height.equalTo(15);
        }];
        self.beginTimeLabel.text = @"00:00";
        self.beginTimeLabel.font = [UIFont systemFontOfSize:11];
        self.beginTimeLabel.textAlignment = 1;
        self.beginTimeLabel.textColor = [UIColor whiteColor];
        
        // 右侧时长
        self.timeLongLabel = [[UILabel alloc] init];
        [effectView addSubview:_timeLongLabel];
        [_timeLongLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.slider.right);
            make.right.equalTo(effectView.right);
            make.centerY.equalTo(self.slider.centerY);
            make.height.equalTo(15);
        }];
        self.timeLongLabel.font = [UIFont systemFontOfSize:11];
        self.timeLongLabel.textAlignment = 1;
        self.timeLongLabel.textColor = [UIColor whiteColor];
        
        // 播放按钮
        self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [effectView addSubview:_playButton];
        [_playButton makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(effectView.centerX);
            make.width.and.height.equalTo(50);
            make.top.equalTo(self.slider.bottom).offset(15);
        }];
        [_playButton addTarget:self action:@selector(didClickedPlayOrSuspend:) forControlEvents:UIControlEventTouchUpInside];
        
        // 上一曲按钮
        self.lastSongButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [effectView addSubview:_lastSongButton];
        [_lastSongButton makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.playButton.centerY);
            make.width.and.height.equalTo(35);
            make.right.equalTo(self.playButton.left).offset(-40);
        }];
        [_lastSongButton setImage:[[UIImage imageNamed:@"player上一首"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        [_lastSongButton addTarget:self action:@selector(didClickedlastSong:) forControlEvents:UIControlEventTouchUpInside];
        
        // 下一曲按钮
        self.nextSongButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [effectView addSubview:_nextSongButton];
        [_nextSongButton makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.playButton.centerY);
            make.width.and.height.equalTo(35);
            make.left.equalTo(self.playButton.right).offset(40);
        }];
        [_nextSongButton setImage:[[UIImage imageNamed:@"player下一首"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        [_nextSongButton addTarget:self action:@selector(didClickedNextSong:) forControlEvents:UIControlEventTouchUpInside];
        
        // 单曲循环or随机播放or顺序播放按钮
        self.OneSongOrOrderButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [effectView addSubview:_OneSongOrOrderButton];
        [_OneSongOrOrderButton makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(effectView.bottom).offset(-25);
            make.left.equalTo(effectView.left).offset(25);
            make.width.and.height.equalTo(30);
        }];
        // 根据当前的播放枚举类型判断
        [self changePlayStyleByStyle:playStyle];
        // 播放模式点击方法
        [self.OneSongOrOrderButton addTarget:self action:@selector(didClickedPlayStyleButton:) forControlEvents:UIControlEventTouchUpInside];
        
        // 播放列表按钮
        self.playListButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [effectView addSubview:_playListButton];
        [_playListButton makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(effectView.right).offset(-25);
            make.bottom.and.width.and.height.equalTo(self.OneSongOrOrderButton);
        }];
        [_playListButton setImage:[[UIImage imageNamed:@"player播放列表"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        [_playListButton addTarget:self action:@selector(didClickedPushMusicList) forControlEvents:UIControlEventTouchUpInside];
        
        
        // 添加navbar上的label
        self.onNavBarLabel = [[UILabel alloc] init];
        self.onNavBarLabel.backgroundColor = [UIColor clearColor];
        self.onNavBarLabel.textColor = [UIColor whiteColor];
        self.onNavBarLabel.font = [UIFont systemFontOfSize:22];
        [self.view addSubview:self.onNavBarLabel];
        
        
        if (isPlaying == YES)
        {
            // 添加定时器旋转
            self.RotateImgTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(timerForRotateSpecialImgView) userInfo:nil repeats:YES];
            // 添加定时器实时改变value
            self.sliderTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerForSlider) userInfo:nil repeats:YES];
        }
    }
    
}


#pragma mark -- 播放列表table
- (void)createMusicListTableView
{
    // 搭载播放列表的view
    self.pushedListView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreeHeight, ScreeWidth, ScreeHeight * 0.5)];
    self.pushedListView.backgroundColor = [UIColor blackColor];
    self.pushedListView.alpha = 0.9;
    [self.view addSubview:_pushedListView];
    
    // 播放列表
    self.musicListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.pushedListView.bounds.origin.y + 30, ScreeWidth, ScreeHeight * 0.5 - 30)];
    [self.pushedListView addSubview:_musicListTableView];
    self.musicListTableView.backgroundColor = [UIColor clearColor];
    self.musicListTableView.rowHeight = 40.0;
    self.musicListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.musicListTableView.delegate = self;
    self.musicListTableView.dataSource = self;
    [self.musicListTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ListTableView"];
    
    // 播放列表cell上的正在播放图标
    self.currentPlayingCellImgView = [[UIImageView alloc] init];
    [self.currentPlayingCellImgView setImage:[UIImage imageNamed:@"player当前歌曲正在放"]];
    [self.musicListTableView addSubview:_currentPlayingCellImgView];
    
    // 收回播放列表按钮
    UIButton *downListButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.pushedListView addSubview:downListButton];
    [downListButton makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.pushedListView.right).offset(-10);
        make.top.equalTo(self.pushedListView.top).offset(5);
        make.width.and.height.equalTo(25);
    }];
    [downListButton setImage:[[UIImage imageNamed:@"player收起列表"] imageWithRenderingMode:1] forState:UIControlStateNormal];
    [downListButton addTarget:self action:@selector(didClickedRecoveMusicList) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -- 播放列表协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    ALPS_SpecialDetailModel *model = [self.listArr objectAtIndex:indexPath.row];
    cell.textLabel.text = model.title;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 如果当前cell是正在播放的
    if (indexPath.row == [self currentMusicIndexOnList])
    {
        [self.currentPlayingCellImgView removeFromSuperview];
        [cell addSubview:_currentPlayingCellImgView];
        [self.currentPlayingCellImgView makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(cell.right).offset(-4);
            make.top.equalTo(cell.top).offset(12);
            make.bottom.equalTo(cell.bottom).offset(-12);
            make.width.equalTo(16);
        }];
        cell.textLabel.textColor = [UIColor colorWithRed:0.350 green:0.529 blue:1.000 alpha:1.000];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self currentMusicIndexOnList] == indexPath.row)// 如果点击的就是当前播放的曲目
    {
        [self didClickedRecoveMusicList];
    }
    else
    {
        ALPS_SpecialDetailModel *model = [self.listArr objectAtIndex:indexPath.row];
        
        [self getSongDataByTrackId:model.trackId];
        
        self.trackId = model.trackId;
        
        [self setNotificationCenterByTrackId:model.trackId ImageURL:model.coverLarge];
        
        [self didClickedRecoveMusicList];
    }
}

#pragma mark -- 获取当前歌曲在播放列表的下标
- (NSInteger)currentMusicIndexOnList
{
    NSInteger count = 0;
    for (ALPS_SpecialDetailModel *model in self.listArr)
    {
        if (model.trackId == self.trackId)
        {
            return count;
        }
        else
        {
            count ++;
        }
    }
    return 0;
}


#pragma mark -- 用model赋值
- (void)giveValueWithModel:(ALPS_PlayMusicModel *)model
{
    NSLog(@"%@", self.playListModel.title);
    //规定字体的大小和样式
    NSDictionary *sizeDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:22], NSFontAttributeName, nil];
    //得到新的frame
    CGRect newRect = [self.playListModel.title boundingRectWithSize:CGSizeMake(10000, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:sizeDic context:nil];
    //根据得到的newRect修改label的高,添加在navbar上的lebel
    self.onNavBarLabel.frame = CGRectMake(ScreeWidth, 60, newRect.size.width, 30);
    //将文字显示到label上
    self.onNavBarLabel.text = self.playListModel.title;
    
    [UIView beginAnimations:@"111" context:NULL];
    [UIView setAnimationDuration:10.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationRepeatCount:1000];
    CGRect frame = self.onNavBarLabel.frame;
    frame.origin.x = -frame.size.width;
    self.onNavBarLabel.frame = frame;
    [UIView commitAnimations];
    
    
    [self.backImgView sd_setImageWithURL:[NSURL URLWithString:self.playListModel.coverLarge]];
    
    [self.SpecialImgView sd_setImageWithURL:[NSURL URLWithString:self.playListModel.coverLarge]];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"string" object:self.playListModel.coverLarge];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"listArr" object:self.listArr];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSInteger minutes = self.playListModel.duration / 60;
    NSInteger seconds = self.playListModel.duration % 60;
    self.timeLongLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", minutes, seconds];
    
    self.player.model = model;
    //    NSLog(@" # # %d", isPlaying);
    
    
}

#pragma mark -- 判断当前播放模式
- (void)changePlayStyleByStyle:(ALPS_PlayStyle)Style
{
    switch (Style)
    {
            // 列表顺序
        case OnListStyle:
            [self.OneSongOrOrderButton setImage:[[UIImage imageNamed:@"player顺序播放"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            break;
            // 单曲循环
        case OneSongStyle:
            [self.OneSongOrOrderButton setImage:[[UIImage imageNamed:@"player单曲循环"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            break;
            // 随机播放
        case RandomStyle:
            [self.OneSongOrOrderButton setImage:[[UIImage imageNamed:@"player随机播放"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            break;
        default:
            break;
    }
}

#pragma mark -- 播放模式按钮点击方法
- (void)didClickedPlayStyleButton:(UIButton *)sender
{
    switch (playStyle)
    {
            // 列表顺序 -> 单曲循环
        case OnListStyle:
        {
            [self.OneSongOrOrderButton setImage:[[UIImage imageNamed:@"player单曲循环"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            playStyle = OneSongStyle;
            // 提示框
            MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            textOnlyHUD.mode = MBProgressHUDModeText;
            textOnlyHUD.labelText = @"已切换至单曲循环";
            [textOnlyHUD hide:YES afterDelay:1.f];
            break;
        }
            // 单曲循环 -> 随机播放
        case OneSongStyle:
        {
            [self.OneSongOrOrderButton setImage:[[UIImage imageNamed:@"player随机播放"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            playStyle = RandomStyle;
            // 提示框
            MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            textOnlyHUD.mode = MBProgressHUDModeText;
            textOnlyHUD.labelText = @"已切换至随机播放";
            [textOnlyHUD hide:YES afterDelay:1.f];
            break;
        }
            // 随机播放 -> 顺序播放
        case RandomStyle:
        {
            [self.OneSongOrOrderButton setImage:[[UIImage imageNamed:@"player顺序播放"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            playStyle = OnListStyle;
            // 提示框
            MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            textOnlyHUD.mode = MBProgressHUDModeText;
            textOnlyHUD.labelText = @"已切换至顺序播放";
            [textOnlyHUD hide:YES afterDelay:1.f];
            break;
        }
        default:
            break;
    }
}


#pragma mark -- timer方法
- (void)timerForSlider
{

    self.slider.value += 1.000 / self.playListModel.duration;
    
    NSInteger minutes = self.playListModel.duration * self.slider.value / 60;
    NSInteger seconds = (long)(self.playListModel.duration * self.slider.value) % 60;
    self.beginTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", minutes, seconds];
    
    //    CGFloat currentTime = CMTimeGetSeconds([self.player.player currentTime]);

    if (self.trackId != 0) {
        if (self.playListModel.duration * self.slider.value >= self.playListModel.duration)
        {
            NSLog(@"自动播放下一首");
            if (playStyle == OneSongStyle)
            {
                self.slider.value = 0;
                [self.player.player seekToTime:CMTimeMakeWithSeconds(0, 1)];
            }
            else
            {
                [self didClickedNextSong:self.nextSongButton];
            }

        }
    }
}

- (void)timerForRotateSpecialImgView
{
    self.SpecialImgView.transform = CGAffineTransformRotate(self.SpecialImgView.transform, M_PI / 180);
}

#pragma mark -- 进度滑条改变监控
- (IBAction)sliderTimeChanged:(UISlider *)sender
{
    
    NSInteger minutes = self.playListModel.duration * sender.value / 60;
    NSInteger seconds = (long)(self.playListModel.duration * sender.value) % 60;
    self.beginTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", minutes, seconds];
    
    [self.player.player seekToTime:CMTimeMakeWithSeconds(sender.value * self.playListModel.duration, 1)];
}

#pragma mark -- 播放/暂停点击方法
- (void)didClickedPlayOrSuspend:(UIButton *)button
{
    if (isPlaying == YES)
    {
        // 暂停
        [self.player pauseCurrentMusic];
        // 改变监控
        isPlaying = NO;
        // 改变按钮样式
        [self.playButton setImage:[[UIImage imageNamed:@"play播放"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        // 定时器失效
        [self.sliderTimer invalidate];
        [self.RotateImgTimer invalidate];
        self.sliderTimer = nil;
        self.RotateImgTimer = nil;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pause" object:nil];
    }
    else
    {
        // 继续播放
        [self.player playCurrentMusic];
        isPlaying = YES;
        [self.playButton setImage:[[UIImage imageNamed:@"player暂停"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        // 重新添加定时器
        self.sliderTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerForSlider) userInfo:nil repeats:YES];
        self.RotateImgTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(timerForRotateSpecialImgView) userInfo:nil repeats:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:nil];
    }
    
    NSLog(@"isPlaying = %d", isPlaying);
    
}

#pragma mark -- 上一曲点击方法
- (void)didClickedlastSong:(UIButton *)button
{
    NSLog(@"上一曲");
    
    if (playStyle == RandomStyle) // 随机播放
    {
        NSInteger newIndex = arc4random() % self.listArr.count;
        
        ALPS_SpecialDetailModel *model = [self.listArr objectAtIndex:newIndex];
        
        [self getSongDataByTrackId:model.trackId];
        
        [self setNotificationCenterByTrackId:model.trackId ImageURL:model.coverLarge];
    }
    else // 单曲循环or顺序播放
    {
        // 如果是列表第一曲
        if ([self currentMusicIndexOnList] == 0)
        {
            ALPS_SpecialDetailModel *model = self.listArr.lastObject;
            
            [self getSongDataByTrackId:model.trackId];
            
            self.trackId = model.trackId;
            
            [self setNotificationCenterByTrackId:model.trackId ImageURL:model.coverLarge];
        }
        else
        {
            ALPS_SpecialDetailModel *model = [self.listArr objectAtIndex:[self currentMusicIndexOnList] - 1];
            
            [self getSongDataByTrackId:model.trackId];
            
            self.trackId = model.trackId;
            
            [self setNotificationCenterByTrackId:model.trackId ImageURL:model.coverLarge];
        }
    }
    
}

#pragma mark -- 下一曲点击方法
- (void)didClickedNextSong:(UIButton *)button
{
    NSLog(@"下一曲");
    
    if (playStyle == RandomStyle) // 随机播放
    {
        NSInteger newIndex = arc4random() % self.listArr.count;
        
        ALPS_SpecialDetailModel *model = [self.listArr objectAtIndex:newIndex];
        
        [self getSongDataByTrackId:model.trackId];
        
        self.trackId = model.trackId;
        
        [self setNotificationCenterByTrackId:model.trackId ImageURL:model.coverLarge];
        
    }
    else // 单曲循环or顺序播放
    {
        // 如果是列表最后一曲
        if ([self currentMusicIndexOnList] == self.listArr.count - 1)
        {
            ALPS_SpecialDetailModel *model = [self.listArr objectAtIndex:0];
            
            [self getSongDataByTrackId:model.trackId];
            
            self.trackId = model.trackId;
            
            [self setNotificationCenterByTrackId:model.trackId ImageURL:model.coverLarge];
        }
        else
        {
            ALPS_SpecialDetailModel *model = [self.listArr objectAtIndex:[self currentMusicIndexOnList] + 1];
            
            [self getSongDataByTrackId:model.trackId];
            
            self.trackId = model.trackId;
            
            [self setNotificationCenterByTrackId:model.trackId ImageURL:model.coverLarge];
        }
    }
}

#pragma mark -- 播放列表推出
- (void)didClickedPushMusicList
{
    [UIView animateWithDuration:0.5 animations:^{
        self.pushedListView.frame = CGRectMake(0, ScreeHeight * 0.5, ScreeWidth, ScreeHeight * 0.5);
    }];
}
#pragma mark -- 播放列表收回
- (void)didClickedRecoveMusicList
{
    [UIView animateWithDuration:0.5 animations:^{
        self.pushedListView.frame = CGRectMake(0, ScreeHeight, ScreeWidth, ScreeHeight * 0.5);
    }];
}



#pragma mark -- 视图即将出现隐藏navbar
- (void)viewWillAppear:(BOOL)animated
{
    CGFloat alpha = 0;
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor colorWithRed:245.0  / 255.0 green:100.0 / 255.0 blue:100.0 / 255.0 alpha:1.0]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.translucent = YES;
}

#pragma mark -------------------- 设置导航栏透明
- (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}

#pragma mark -- 摇一摇自动下一首
- (BOOL)canBecomeFirstResponder{
    return YES;
}
- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    if (UIEventSubtypeMotionShake == motion) {
        [self didClickedNextSong:self.nextSongButton];
    }
}

#pragma mark --- 远程线控事件
- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    if (event.type == UIEventTypeRemoteControl) {
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:{
//                if (isPlaying == YES) {
//                    [self.playerManager pause];
//                    self.playView.play = NO;
//                }
//                else{
//                    [self.playerManager play];
//                    self.playView.play = YES;
//                }
                [self didClickedPlayOrSuspend:self.playButton];
            }
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [self didClickedNextSong:self.nextSongButton];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self didClickedlastSong:self.lastSongButton];
                break;
                
            default:
                break;
        }
    }
}

#pragma mark -- 视图即将消失变回原来的导航栏
- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.navigationController.navigationBar.translucent = NO;
    
    [self.sliderTimer invalidate];
    self.sliderTimer = nil;
    [self.RotateImgTimer invalidate];
    self.RotateImgTimer = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


/*
 #pragma mark - Navigation
 
  In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  Get the new view controller using [segue destinationViewController].
  Pass the selected object to the new view controller.
 }
 */

@end
